package vn.bang.utility;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public final class EntityManagerFactoryUtil {

	/**
	 * @param persistenceUnit
	 *            a String object representing persistenceUnit.
	 * @return The EntityManagerFactory object representing entity manager
	 *         factory of the persistence unit parameter string. If not exist,
	 *         will create a new entity manager factory.
	 */
	static public synchronized EntityManagerFactory getEntityManagerFactory(
			final String persistenceUnit) {
		if (null == lstEntityManagerFactory.get(persistenceUnit)) {
			lstEntityManagerFactory.put(persistenceUnit,
					Persistence.createEntityManagerFactory(persistenceUnit));
		}
		return lstEntityManagerFactory.get(persistenceUnit);
	}

	/**
	 * Close the EntityManagerFactory object representing entity manager factory
	 * of the persistence unit parameter string.
	 * 
	 * @param persistenceUnit
	 *            a String object representing persistenceUnit.
	 */
	static public synchronized void closeEntityManagerFactory(
			final String persistenceUnit) {
		if (null != lstEntityManagerFactory) {
			EntityManagerFactory entityManagerFactory = lstEntityManagerFactory
					.get(persistenceUnit);
			if (null != entityManagerFactory) {
				closeEntityManagerFactory(entityManagerFactory);
				lstEntityManagerFactory.remove(persistenceUnit);
			}
		}
	}

	/**
	 * Close the EntityManagerFactory object.
	 * 
	 * @param entityManagerFactory
	 *            a EntityManagerFactory object to be closed.
	 */
	static public void closeEntityManagerFactory(
			final EntityManagerFactory entityManagerFactory) {
		if (null != entityManagerFactory && entityManagerFactory.isOpen()) {
			entityManagerFactory.close();
		}
	}

	private static Map<String, EntityManagerFactory> lstEntityManagerFactory = new HashMap<String, EntityManagerFactory>();

	/**
	 * Prevent constructor.
	 */
	private EntityManagerFactoryUtil() {
	}

}